package cn.chinaflame.pagodas.web;

import cn.chinaflame.pagodas.Result.Requests;
import cn.chinaflame.pagodas.service.SessionService;
import cn.chinaflame.pagodas.spring.ApplicationContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

/**
 * @author created by boming
 * @date 2018年1月17日 下午1:35:21
 */
public class SessionFactory<E> {


    private static final Logger log = LoggerFactory.getLogger(SessionFactory.class);

    /**
     * 创建session对象
     *
     * @param sessionId
     * @param userid
     * @param userProjectType
     * @param object
     */
    public static void generateSession(String userid, String userProjectType, Object object) {
        log.info("创建session对象userid:{},userProjectType:{},object:{}", userid, userProjectType, object);
        SessionService sessionService = ApplicationContextHolder.getBean(SessionService.class);
        String sessionId = Requests.getSession(true).getId();
        log.info("创建的sessionId:{}", sessionId);
        sessionService.generateSession(sessionId, userid, userProjectType, object);
    }

    /**
     * 获取登录用户对象
     *
     * @param sessionid
     * @param userProjectType
     * @param c
     * @return
     */
    public static <E> E getUserObj(String sessionid, String userProjectType, Class<E> c) {
        log.info("获取session保存的用户对象sessionid:{},userProjectType:{},c:{}", sessionid, userProjectType, c);
        SessionService sessionService = ApplicationContextHolder.getBean(SessionService.class);
        Object o = sessionService.getUserObj(sessionid, userProjectType);
        try {
            E e = c.newInstance();
            BeanUtils.copyProperties(o, e);
            return e;
        } catch (ReflectiveOperationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取登录用户对象
     *
     * @param sessionid
     * @param userProjectType
     * @param c
     * @return
     */
    public static <E> E getUserObj(String userProjectType, Class<E> c) {
        log.info("获取session保存的用户对象userProjectType:{},c:{}", userProjectType, c);
        return null;
//		return getUserObj(Requests.getUserSessionId(), userProjectType, c);
    }
}
